import IndexCard from '@/pages/Home/components/IndexCard'
import {
  CustomerStatisticsQueryDTO,
  getCustomerStatistics,
  getCustomerStatisticsByChannel,
  getOrderByGoods,
  getRankBySeller,
} from '@/services/StatisticsService'
import { rangePresets } from '@/utils/DateRangeUtils'
import { getStatisticsSum } from '@/utils/StatisticsUtil'
import { Column, Line, Pie } from '@ant-design/charts'
import { SearchOutlined } from '@ant-design/icons'
import { PieConfig } from '@ant-design/plots'
import { useModel } from '@umijs/max'
import { useRequest } from 'ahooks'
import { Button, Card, Col, DatePicker, Divider, Row, Segmented } from 'antd'
import { Empty } from 'antd/lib'
import dayjs from 'dayjs'
import React, { useEffect, useState } from 'react'

const Index: React.FC = () => {
  const { initialState } = useModel('@@initialState')
  const getCustomerStatisticsByChannelRequest = useRequest(getCustomerStatisticsByChannel, { manual: true })
  const {
    data,
    loading: getCustomerLoading,
    run: runGetCustomerStatistics,
  } = useRequest(getCustomerStatistics, { manual: true })
  const getOrderByGoodsRequest = useRequest(getOrderByGoods, { manual: true })
  const getRankBySellerRequest = useRequest(getRankBySeller, { manual: true })
  const [dateRange, setDateRange] = useState<CustomerStatisticsQueryDTO>({
    startDay: dayjs().subtract(30, 'day'),
    endDay: dayjs(),
    dateLimit: 31,
  })

  const [channelType, setChannelType] = useState<string | number>('customer_count')

  const fetchStatisticsData = () => {
    getCustomerStatisticsByChannelRequest.run(dateRange)
    runGetCustomerStatistics(dateRange)
    getOrderByGoodsRequest.run(dateRange)
    getRankBySellerRequest.run(dateRange)
  }
  useEffect(() => {
    fetchStatisticsData()
  }, [])

  const config = {
    data: [
      ...getStatisticsSum(data || [], ['customer_count'], (d, value) => ({
        name: '客资数量',
        date: d.date,
        value: value[0],
      })),
      ...getStatisticsSum(data || [], ['order_count'], (d, value) => ({
        name: '订单数量',
        date: d.date,
        value: value[0],
      })),
    ],
    // padding: 'auto',
    xField: 'date',
    yField: 'value',
    seriesField: 'name',
    xAxis: {
      // type: 'timeCat',
      tickCount: 5,
    },
    smooth: true,
    // @TODO 后续会换一种动画方式
    animation: {
      appear: {
        animation: 'path-in',
        duration: 3000,
      },
    },
  }

  const pieConfig: PieConfig = {
    appendPadding: 10,
    data: getCustomerStatisticsByChannelRequest.data || [],
    angleField: channelType.toString(),
    colorField: 'channel_name',
    radius: 0.9,
    label: {
      type: 'inline',
      offset: '-30%',
      content: ({ percent }) => `${(percent * 100).toFixed(0)}%`,
      style: {
        fontSize: 14,
        textAlign: 'center',
      },
    },
    interactions: [
      {
        type: 'element-active',
      },
    ],
  }

  const columnConfig = {
    data: [
      ...(data || []).map(({ date, real_price }) => ({ name: '业绩金额', date, price: real_price })),
      ...(data || []).map(({ date, real_price, order_count }) => ({
        name: '均价',
        date,
        price: real_price / order_count,
      })),
    ],
    autoFit: true,
    isGroup: true,
    xField: 'date',
    yField: 'price',
    seriesField: 'name',
    xAxis: {
      label: {
        autoHide: true,
        autoRotate: false,
      },
    },
    meta: {
      date: {
        alias: '日期',
      },
      price: {
        alias: '金额',
      },
    },
    slider: {
      start: 0.8,
      end: 1,
    },
  }

  const orderByGoodsColumnConfig = {
    data: [
      ...(getOrderByGoodsRequest.data || []).map(({ goods_name, real_price }) => ({
        name: '业绩金额',
        goods_name,
        money: real_price,
      })),
      ...(getOrderByGoodsRequest.data || []).map(({ goods_name, order_count, real_price }) => ({
        name: '均价',
        goods_name,
        money: real_price / order_count,
      })),
    ],
    autoFit: true,
    isGroup: true,
    xField: 'goods_name',
    yField: 'money',
    seriesField: 'name',
    xAxis: {
      label: {
        autoHide: true,
        autoRotate: false,
      },
    },
  }

  const getDateRangePicker = () => {
    return (
      <div>
        <DatePicker.RangePicker
          presets={rangePresets}
          value={[dateRange.startDay, dateRange.endDay]}
          onChange={(dates) => {
            if (dates) {
              // @ts-ignore
              setDateRange({
                startDay: dates[0],
                endDay: dates[1],
                dateLimit: dates[1].diff(dates[0], 'day') + 1,
              })
            }
          }}
          onOk={() => {}}
        />
        <Button style={{ marginLeft: '5px' }} icon={<SearchOutlined />} onClick={fetchStatisticsData}></Button>
      </div>
    )
  }

  return (
    <>
      <Row gutter={[16, 16]} justify="center">
        <Col span={24} lg={16}>
          <Card hoverable title={`👏欢迎回来! ${initialState?.userinfo?.userName}!`} extra={getDateRangePicker()}>
            <Row gutter={[16, { xs: 16, sm: 16 }]} justify="center">
              <Col style={{ display: 'flex', justifyContent: 'center' }} lg={8} md={8} xs={24} sm={24}>
                <IndexCard
                  title="获取客资"
                  value={(data || []).reduce((total, curr) => total + curr.customer_count, 0)}
                  icon="https://leuan.top/files/assets/icon/kehu.svg"
                />
              </Col>
              <Col style={{ display: 'flex', justifyContent: 'center' }} lg={8} md={8} xs={24} sm={24}>
                <IndexCard
                  title="订单数量"
                  value={(data || []).reduce((total, curr) => total + curr.order_count, 0)}
                  icon="https://leuan.top/files/assets/icon/hetongdingdan.svg"
                />
              </Col>
              <Col style={{ display: 'flex', justifyContent: 'center' }} lg={8} md={8} xs={24} sm={24}>
                <IndexCard
                  title="业绩金额"
                  value={(data || []).reduce((total, curr) => total + curr.real_price, 0).toFixed(1)}
                  icon="https://leuan.top/files/assets/icon/qushi.svg"
                />
              </Col>
            </Row>
            <Divider />
            <Row>
              <Col span={24}>
                <Line {...config} />
              </Col>
            </Row>
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title="业绩" hoverable style={{ maxHeight: '500px', overflowY: 'hidden' }}>
            <Empty />
          </Card>
        </Col>
      </Row>
      <Row gutter={[16, 8]} style={{ marginTop: '16px' }}>
        <Col md={12} lg={8} xs={24} sm={24}>
          <Card hoverable style={{ height: '500px' }} title="每日业绩汇总">
            <Column {...columnConfig} />
          </Card>
        </Col>
        <Col md={12} lg={8} xs={24} sm={24}>
          <Card hoverable style={{ height: '500px' }} title="渠道数据汇总">
            <Segmented
              block
              action={channelType.toString()}
              options={[
                { label: '客资数量', value: 'customer_count' },
                { label: '订单数量', value: 'order_count' },
                { label: '套系金额', value: 'goods_price' },
                { label: '订单金额', value: 'real_price' },
                { label: '收款金额', value: 'already_pay' },
              ]}
              onChange={setChannelType}
            />
            <Pie {...pieConfig}></Pie>
          </Card>
        </Col>
        <Col md={12} lg={8} xs={24} sm={24}>
          <Card hoverable style={{ height: '500px' }} title="套系数据汇总">
            <Column {...orderByGoodsColumnConfig} />
          </Card>
        </Col>
      </Row>
    </>
  )
}

export default Index
